<?php
/**
 * Master进程启动
 * Created on 2022/8/26 9:36
 * Created by 管昌虎
 * Email guanchanghu626@163.com
 * @author 管昌虎
 */

namespace GuanChanghu\Library\Events;


use GuanChanghu\Library\Services\Thrift\ClientService;
use GuanChanghu\Library\Sockets\Thrift\Server as TServer;
use GuanChanghu\Library\Sockets\Thrift\ServerTransport;
use GuanChanghu\Library\Sockets\Thrift\TFramedTransportFactory;
use GuanChanghu\Library\Thrift\Client\ClientProcessor;
use Hhxsv5\LaravelS\Swoole\Events\ServerStartInterface;
use Swoole\Http\Server;
use Thrift\Factory\TBinaryProtocolFactory;

/**
 * @author 管昌虎
 * Class ServerStartEvent
 * @tag encryption free
 * @package GuanChanghu\Library\Events
 * Created on 2022/8/26 9:37
 * Created by 管昌虎
 * Email guanchanghu626@163.com
 */
class ServerStartEvent implements ServerStartInterface
{
    /**
     * ServerStartEvent constructor.
     */
    public function __construct()
    {

    }

    /**
     * @param Server $server
     * @return void
     */
    public function handle(Server $server)
    {
        $this->thriftEnabled($server);
    }

    /**
     * @param Server $server
     * @return void
     */
    protected function thriftEnabled(Server $server): void
    {
        if (!env('THRIFT_SERVICE_ENABLED')) {
            return;
        }

        // 初始化thrift
        $processor = new ClientProcessor(new ClientService());
        $tFactory = new TFramedTransportFactory();
        $pFactory = new TBinaryProtocolFactory();
        // 监听本地 9999 端口，等待客户端连接请求
        $transport = new ServerTransport($server, 'localhost', 9999);
        $tServer = new TServer($processor, $transport, $tFactory, $tFactory, $pFactory, $pFactory);
        $tServer->serve();
    }
}
